import Request from './request'

const http = new Request();
const token = uni.getStorageSync('token')
console.log('token',token)
let baseUrl = 'http://vue_admin.shenzhenbenwo.com'; //公共baseUrl
try {
	if (location.hostname == 'localhost') {
		baseUrl = ''
	}
} catch (e) {

}

// request全局参数设置
http.setConfig((config) => {
	/* 设置全局配置 */
	config.baseUrl = baseUrl;
	config.header = {
		...config.header,
	};
	return config;
});

http.interceptor.request((config) => {
	/* 请求之前拦截器 */
	// token 拼接在header头
	// config.header['token'] = uni.getStorageSync('token');
	// Authorization  就是后台返回的token
	// config.header['token'] = uni.getStorageSync('token');
	// Authorization  就是后台返回的token码

	config.header['Authorization']= uni.getStorageSync('token') || 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJjbGllbnQudnVlYWRtaW4iLCJhdWQiOiJzZXJ2ZXIudnVlYWRtaW4iLCJpYXQiOjE2MzA1NDcyNTksImV4cCI6MTYzMDk3OTI1OSwidWlkIjoie1wiaWRcIjo3NSxcImdyb3VwX2lkXCI6MCxcInVzZXJuYW1lXCI6XCJcXHU2NzY4XFx1OTZjNFwiLFwibmlja25hbWVcIjpcIlVOUmdIUlwiLFwibW9iaWxlXCI6XCIxNzY4MDU3NDMwNFwiLFwiZW1haWxcIjpcIlVOUmdIUkBxcS5jb21cIixcInBhc3N3b3JkXCI6XCJhZjE3NGU2OTdkNGMxYThlZGQwZmM1NjQyM2QyMTUzMFwiLFwiYXZhdGFyXCI6XCJcIixcImxldmVsXCI6MSxcImdlbmRlclwiOjEsXCJtb25leVwiOlwiMC4wMFwiLFwiY29tbWlzc2lvblwiOlwiMC4wMFwiLFwic2NvcmVcIjowLFwiYmlydGhkYXlcIjpudWxsLFwiYmlvXCI6bnVsbCxcInNzcVwiOm51bGwsXCJhZGRyZXNzXCI6bnVsbCxcInBpZFwiOjUyLFwiZGVwdGhcIjpcIjUyXCIsXCJpbnZpdGVfY29kZVwiOlwiWlB4R0hvXCIsXCJzdGF0dXNcIjpcIjFcIixcInByZXZ0aW1lXCI6MTYzMDQ2NjIyNixcInN1Y2Nlc3Npb25zXCI6MSxcIm1heHN1Y2Nlc3Npb25zXCI6MSxcImxvZ2luX2lwXCI6XCIxMTMuODguMTM4Ljc5XCIsXCJsb2dpbl90aW1lXCI6MTYzMDU0NzI1OSxcImpvaW5faXBcIjpcIjExMy44OC4xMzguNzlcIixcImpvaW5fdGltZVwiOjE2MzA0NjYyMjYsXCJsb2dpbmZhaWx1cmVcIjowLFwiY3JlYXRlX3RpbWVcIjpcIjIwMjEtMDktMDEgMTE6MTc6MDZcIn0ifQ.Wnz3gyTODLFRRPp9QUGPe-7EYwI75nooU6b2EpdocBE';
	return config;
}, error => {
	return Promise.reject(error)
})

http.interceptor.response(async (response) => {
	/* 请求之后拦截器 */
	switch (response.data.code || response.data.status) {

		case 1:
			return response.data;
		case 101:

			break;
		case 200:
			return response.data;
		case 203:
			break;
		case 401:
			console.log("token过期");
			break;
		case 400:

			return Promise.reject(response.data.msg);
			break;
		case 201:
		case 404:

			return Promise.reject(response.data.msg);
		case 500:

			return Promise.reject(response.data.msg);
		default:
			uni.showToast({
				icon: 'none',
				title: response.data.msg
			});
			return response.data;
	}
}, (error) => {
	console.log(error);
	//console.log('http requset error:',JSON.stringify(JSON.parse(error)))
	//监听401状态，则是401跳到登录
	if (error.statusCode == 401 || error.data.code == 401) {
		uni.reLaunch({
			url: '/pages/Mine/login',
			fail(e) {
				console.log(e)
			}
		})
	}
	return Promise.reject(error)
});

export {
	http,
	baseUrl,
}
